package com.fastCms.business.bim.manage.impl;

import com.fastCms.business.frame.constant.CommonConst;
import com.fastCms.business.bim.manage.DataMockManageService;
import com.fastCms.business.bim.pojo.entity.DataMock;
import com.fastCms.business.bim.pojo.po.DataMockListPO;
import com.fastCms.business.bim.pojo.po.DataMockSavePO;
import com.fastCms.business.bim.service.DataMockService;
import com.fastCms.business.frame.response.ApiResponse;
import com.fastCms.business.frame.response.ResponseUtil;
import com.fastCms.business.frame.utils.CommonsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Component
@Slf4j
public class DataMockManageServiceImpl implements DataMockManageService {

    @Autowired
    private DataMockService dataMockServiceImpl;

    @Override
    public ApiResponse<DataMock> getByCode(String code) {
        DataMock dataMock = dataMockServiceImpl.findByCode(code);
        if (null == dataMock) {
            return ResponseUtil.fail("数据未配置");
        }
        //使用MOCK数据
        if (dataMock.getUseMock() == 1) {
            return ResponseUtil.success(dataMock);
            //走真实数据
        } else {
            return ResponseUtil.success(dataMock);
        }
    }

    @Override
    public ApiResponse<List<DataMock>> list(DataMockListPO dataMockListPO) {
        List<DataMock> dataMockList = dataMockServiceImpl.findValidAll(dataMockListPO.getSearch());
        return ResponseUtil.success(dataMockList);
    }

    @Override
    public ApiResponse<Boolean> saveOrUpdate(DataMockSavePO dataMockSavePO) {
        if (null == dataMockSavePO) {
            return ResponseUtil.fail("编号不能为空");
        }
        DataMock dataMock = dataMockServiceImpl.findByCode(dataMockSavePO.getCode());
        if (null == dataMock) {
            DataMock area = new DataMock();
            BeanUtils.copyProperties(dataMockSavePO, area);
            CommonsUtil.initEntity(area);
            area.setUseMock(1);
            dataMockServiceImpl.save(area);
        } else {
            dataMock.setMockData(dataMockSavePO.getMockData());
            dataMockServiceImpl.updateById(dataMock);
        }
        return ResponseUtil.success(true);
    }

    @Override
    public ApiResponse<Boolean> delete(String code) {
        DataMock dataMock = dataMockServiceImpl.findByCode(code);
        if (null == dataMock) {
            return ResponseUtil.fail("数据不存在");
        }
        dataMock.setState(CommonConst.STATE.INVALID);
        boolean b = dataMockServiceImpl.updateById(dataMock);
        return ResponseUtil.success(b);
    }

}
